package utilities;

import utilities.Uporabnik;
import utilities.controller.UporabnikManager;

import java.io.IOException;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class prijavaServlet
 */
@WebServlet("/prijavaServlet")
public class prijavaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@PersistenceUnit( unitName="VajaJPA" )
	private EntityManagerFactory emf;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public prijavaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String geslo = request.getParameter("geslo");
		UporabnikManager um = new UporabnikManager(emf);
		//Uporabnik("Janez", "Novak", "moski", "Kranjska cesta 3", "1989", "2012", "univerzitetni", "1", "racininf",  email, geslo, "admin");
		try {
			Uporabnik up = um.vrniUporabnika(email, geslo);
			if (up != null) {
				HttpSession session = request.getSession();
				session.setAttribute("uporabnik", up);
				response.sendRedirect("index.jsp");
				
			} else {
				response.sendRedirect("prijava.jsp");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			response.sendRedirect("prijava.jsp");
		}
		
	}

}
